# -*- python -*-
# ex: set syntax=python:

# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# It has one job: define a dictionary named BuildmasterConfig. This
# dictionary has a variety of keys to control different aspects of the
# buildmaster. They are documented in docs/config.xhtml .

from buildbot.changes import gitpoller
from buildbot.status.mail import MailNotifier
from buildbot import scheduler

from common import chromium_utils

from master import master_utils
from master import slaves_list
from master.factory import drmemory_factory
from master.factory import chromium_factory

import config
import master_site_config
ActiveMaster = master_site_config.DrMemory

MASTER_HOST = ActiveMaster.master_host
MAIL_NOTIFIER = ActiveMaster.is_production_host
MASTER_PORT = ActiveMaster.master_port

# This is the dictionary that the buildmaster pays attention to. We also use
# a shorter alias to save typing.
c = BuildmasterConfig = {}

config.DatabaseSetup(c, require_dbconfig=ActiveMaster.is_production_host)

# 'slavePortnum' defines the TCP port to listen on. This must match the value
# configured into the buildslaves (with their --master option)
c['slavePortnum'] = ActiveMaster.slave_port

slaves = slaves_list.SlavesList('slaves.cfg', 'DrMemory')


####### CHANGESOURCES

if ActiveMaster.is_production_host:
  from buildbot.changes.gitpoller import GitPoller
  drm_poller = GitPoller(repourl=drmemory_factory.drm_giturl,
                         workdir="gitpoller",
                         gitbin=chromium_utils.GIT_BIN,
                         pollinterval=60,
  )
  c['change_source'] = [ drm_poller ]


####### SCHEDULERS

## configure the Schedulers
MAINBOTS = [
    ["win", ["xp", "vista_x64", "7_x64", "8_x64"]],
    ["linux", ["lucid_x64"]],
    ["mac", ["mavericks_x64"]],
]
DRM_BUILDERS = []
for (os, os_versions) in MAINBOTS:
  for version in os_versions:
    DRM_BUILDERS.append("%s-%s-drm" % (os, version))

# We expect these bots to be green.  xp and vista aren't green yet, and the
# stability bots have regressed.
STABLE_BUILDERS = ["win-builder", "linux-builder",
                   "win-7_x64-drm", "linux-lucid_x64-drm",
                   "mac-builder", "mac-mavericks_x64-drm",
                   "linux-cr-builder", "linux-cr",
                   "win7-cr-builder", "win7-cr",
                   # If we add more *-cr bots we could consider sharing a
                   # single cr build, but these build just once a week, and
                   # only target component-config tests (~15 mins to build),
                   # so sharing wouldn't buy us much.
                   "win8-cr-builder", "win8-cr",
                   ]

c['schedulers'] = []
c['schedulers'].append(scheduler.Scheduler(
                           name="all",
                           branch='master',
                           treeStableTimer=60,
                           builderNames=(["win-builder"] +
                                         ["linux-builder"] +
                                         ["mac-builder"] +
                                         DRM_BUILDERS)))
c['schedulers'].append(scheduler.Periodic(
                           name="periodic",
                           branch='master',
                           periodicBuildTimer=12*60*60,  # Every 12 hours
                           builderNames=DRM_BUILDERS))
c['schedulers'].append(scheduler.Periodic(
                           name="periodic_stable",
                           branch='master',
                           periodicBuildTimer=2*60*60,  # Every 2 hours
                           builderNames=["win8-cr", "win7-cr", "linux-cr"]))
c['schedulers'].append(scheduler.Nightly(
                           name='weekly',
                           branch='master',
                           dayOfWeek=6,  # Monday=0, Sunday=6
                           properties={'is_weekly': True},
                           builderNames=['win8-cr-builder',
                                         'win7-cr-builder',
                                         'linux-cr-builder']))


####### BUILDERS

F_DRM = drmemory_factory.CreateDrMFactory
F_DRMPACK = drmemory_factory.CreateDrMPackageFactory
F_WIN_CR = drmemory_factory.CreateWinChromeFactory
F_LINUX_CR = drmemory_factory.CreateLinuxChromeFactory

def win_cr_build():
  return chromium_factory.ChromiumFactory('src/build', 'win32')

f_win_cr_builder = win_cr_build().ChromiumFactory(
    target='Debug',
    slave_type='Builder',
    project='all.sln;chromium_builder_dbg_drmemory_win',
    factory_properties={
        'lkgr': True,  # Try to avoid bad Chrome revs.
        'gclient_env': {
            'GYP_DEFINES': 'build_for_tool=drmemory component=shared_library'
        },
        'package_pdb_files': True,
        },
    )

def linux_cr_build():
  return chromium_factory.ChromiumFactory('src/out', 'linux2')

f_linux_cr_builder = linux_cr_build().ChromiumFactory(
    target='Release',
    slave_type='Builder',
    options=(['--build-tool=ninja', '--compiler=goma'] +
             drmemory_factory.LINUX_CHROME_TESTS),
    factory_properties={
        'lkgr': True,  # Try to avoid bad Chrome revs.
        'gclient_env': {
            'GYP_DEFINES': 'build_for_tool=drmemory component=shared_library',
        },
    },
)

c['builders'] = []

# Bots that run on every commit: the pre-commit suite and the packager.
for (os, os_versions) in MAINBOTS:
  c['builders'].append({'name': '%s-builder' % os,
                        'factory': F_DRMPACK(os)})
  for version in os_versions:
    c['builders'].append({'name': '%s-%s-drm' % (os, version),
                          'factory': F_DRM(os)})

# Miscellaneous stability bots that run periodically.
c['builders'].append({'name': 'win7-cr-builder',
                      'factory': f_win_cr_builder,
                      'auto_reboot': False,
                      })

c['builders'].append({'name': 'win7-cr',
                      'factory': F_WIN_CR('win7-cr-builder'),
                      'auto_reboot': True,  # Kill stale processes
                      })

c['builders'].append({'name': 'win8-cr-builder',
                      'factory': f_win_cr_builder,
                      'auto_reboot': False,
                      })

c['builders'].append({'name': 'win8-cr',
                      'factory': F_WIN_CR('win8-cr-builder'),
                      'auto_reboot': True,  # Kill stale processes
                      })

c['builders'].append({'name': 'linux-cr-builder',
                      'factory': f_linux_cr_builder,
                      'auto_reboot': False,
                      })

c['builders'].append({'name': 'linux-cr',
                      'factory': F_LINUX_CR(),
                      'auto_reboot': False,
                      })


####### BUILDSLAVES

for builder in c['builders']:
  builder['slavenames'] = slaves.GetSlavesName(builder=builder['name'])

# The 'slaves' list defines the set of allowable buildslaves. List all the
# slaves registered to a builder. Remove dupes.
c['slaves'] = master_utils.AutoSetupSlaves(c['builders'],
                                           config.Master.GetBotPassword())

# Make sure everything works together.
master_utils.VerifySetup(c, slaves)


####### STATUS TARGETS

# The 'buildbotURL' string should point to the location where the buildbot's
# internal web server (usually the html.Waterfall page) is visible. This
# typically uses the port number set in the Waterfall 'status' entry, but
# with an externally-visible host name which the buildbot cannot figure out
# without some help.

# Must come before AutoSetupMaster().
c['buildbotURL'] = ActiveMaster.buildbot_url

# Adds common status and tools to this master.
master_utils.AutoSetupMaster(c, ActiveMaster)

# Satisfy the mock testing which will check whether command strings have
# unset properties but won't run the steps that set those properties:
c['properties']['pkg_buildnum'] = '<unset>'
c['properties']['package_base'] = '<unset>'

c['status'].append(MailNotifier(fromaddr="timurrrr+drm+buildbot@google.com",
                   lookup="gmail.com", # add @gmail.com if "@" is not in the commiter's ID
                   extraRecipients=['drmemory-devs@googlegroups.com'],
                   builders=STABLE_BUILDERS,
                   mode='problem'))

# Keep last build logs, the default is too low.
c['buildHorizon'] = 1000
c['logHorizon'] = 500
# Must be at least 2x the number of slaves.
c['eventHorizon'] = 200
# Must be at least 1x the number of builds listed in console.
c['buildCacheSize'] = 60


####### DEBUGGING OPTIONS

# if you set 'debugPassword', then you can connect to the buildmaster with
# the diagnostic tool in contrib/debugclient.py . From this tool, you can
# manually force builds and inject changes, which may be useful for testing
# your buildmaster without actually commiting changes to your repository (or
# before you have a functioning 'sources' set up). The debug tool uses the
# same port number as the slaves do: 'slavePortnum'.

#c['debugPassword'] = 'debugpassword'

# if you set 'manhole', you can ssh into the buildmaster and get an
# interactive python shell, which may be useful for debugging buildbot
# internals. It is probably only useful for buildbot developers. You can also
# use an authorized_keys file, or plain telnet.
#from buildbot import manhole
#c['manhole'] = manhole.PasswordManhole('tcp:9999:interface=127.0.0.1',
#                                       'admin', 'password')


####### PROJECT IDENTITY

# the 'projectName' string will be used to describe the project that this
# buildbot is working on. For example, it is used as the title of the
# waterfall HTML page. The 'projectURL' string will be used to provide a link
# from buildbot HTML pages to your project's home page.

c['projectName'] = ActiveMaster.project_name
c['projectURL'] = config.Master.project_url
